package com.example.sqlSession;

import com.example.config.BoundSql;
import com.example.pojo.Configuration;
import com.example.pojo.MappedStatement;
import com.example.uitls.GenericTokenParser;
import com.example.uitls.ParameterMapping;
import com.example.uitls.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

/**
 * 该类实现接口Executor
 * 1.因为执行sql的前置准备1、注册驱动，获取连接；2、获取sql语句、转换sql语句： #{}-->? 3：获取预处理对象；4：参数处理的操作是相同
 * 2.提取方法preparedStatementHandle()用来预处理前置准备，该方法返回之为PreparedStatement；
 * 3.executeUpdate();方法返回类型为int,这里用Integer接接收才可转换成 E
 *
 * @author kangshuai
 */
public class SimpleExecutor implements Executor {


    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {

        PreparedStatement preparedStatement = preparedStatementHandle(configuration, mappedStatement, params);

        // 5. 执行sql
        ResultSet resultSet = preparedStatement.executeQuery();
        String resultType = mappedStatement.getResultType();
        Class<?> resultTypeClass = getClassType(resultType);

        ArrayList<Object> objects = new ArrayList<>();

        // 6. 封装返回结果集
        while (resultSet.next()) {
            Object object = resultTypeClass.getDeclaredConstructor().newInstance();
            //元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int j = 1; j <= metaData.getColumnCount(); j++) {

                //使用反射或者内省，根据数据库表和实体的对应关系，完成封装
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(metaData.getColumnName(j), resultTypeClass);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(object, resultSet.getObject(metaData.getColumnName(j)));
            }
            objects.add(object);
        }

        return (List<E>) objects;
    }

    @Override
    public <E> E update(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        PreparedStatement preparedStatement = preparedStatementHandle(configuration, mappedStatement, params);
        // 5. 执行sql
        Integer resultSet = preparedStatement.executeUpdate();
        return (E) resultSet;
    }


    /**
     * 完成对#{}的解析工作：1.将#{}使用？进行代替，2.解析出#{}里面的值进行存储
     *
     * @param sql
     * @return
     */
    private BoundSql getBoundSql(String sql) {
        //标记处理类：配置标记解析器来完成对占位符的解析处理工作
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        //解析出来的sql
        String parseSql = genericTokenParser.parse(sql);
        //#{}里面解析出来的参数名称
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();

        BoundSql boundSql = new BoundSql(parseSql, parameterMappings);
        return boundSql;
    }


    private Class<?> getClassType(String parameterType) throws Exception {
        if (parameterType != null) {
            Class<?> aClass = Class.forName(parameterType);
            return aClass;
        }
        return null;
    }


    private PreparedStatement preparedStatementHandle(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {

        //1.注册驱动，获取连接
        Connection connection = configuration.getDataSource().getConnection();

        //2. 获取sql语句、转换sql语句： #{}-->?
        BoundSql boundSql = getBoundSql(mappedStatement.getSql());

        //3.获取预处理对象
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());

        // 4. 设置参数
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();

        //获取到了参数的全路径
        Class<?> parameterTypeClass = getClassType(mappedStatement.getParameterType());


        for (int i = 0; i < parameterMappingList.size(); i++) {

            String content = parameterMappingList.get(i).getContent();
            //反射
            Field field = parameterTypeClass.getDeclaredField(content);

            //暴力访问
            field.setAccessible(true);
            Object o = field.get(params[0]);

            preparedStatement.setObject(i + 1, o);
        }
        return preparedStatement;
    }

}
